const dbconfig = require('../util/dbconfig')

// const Core = require('@alicloud/pop-core')//阿里大于接口
// const config = require('../util/aliconfig')
// let client =new Core(config.alicloud)//配置
// let requestOption={
//     method:'POST'
// }
//阿里大于大发送接口 暂时没用
// sendCodeDayu=(req,res)=>{
//     let code=rand(1000,9999);
//     var params={
//         "RegionID":1,
//         "PhoneNumbers":1,
//         "SignName":1,
//         "TemplateCode":1,
//         "TemplateParam":1,
//     }
//     client.request('SendSms',params,requestOption).then((result)=>{
//         console.log(result)
//         if(result.code=='ok'){
//             res.send({
//                 'code':200,
//                 'msg':"发送成功"
//             })
//             validatePhoneCode.push({
//                 'phone':phone,
//                 'code':code
//             })
//         }else{
//             res.send({
//                 'code':400,
//                 'msg':"发送失败"
//             })
//         }
//     })

// }
function rand(min,max){
    return Math.floor(Math.random()*(max-min))+min
}

//验证手机号是否发送过验证码
validatePhoneCode = [];
let sendCodeP=(phone)=>{
    for(var item of validatePhoneCode){
        if (phone==item.phone){
            return true
        }
    }
    return false
}
//找code和phone
let findCodeAndPhone =(code,phone)=>{
    for(var item of validatePhoneCode){
        if (phone==item.phone&&code==item.code){
            return 'login'
        }
    }
    return 'error'
}
//检测是否是第一次登录
let phoneLoginBind=async(phone)=>{
    let sql="select * from user where username=? or phone=?"
    let sqlarr=[phone,phone]
    let res =await dbconfig.sySqlConnect(sql,sqlarr)
    if(res.length){
        res[0].userinfo= await getUserInfo(res[0].id)
        return res
    }else{
        //第一次登录入库
        let user = await regUser(phone)
        res[0].userinfo= await createUserInfo(user[0].id)
        return res
    }
}
//用户注册
let regUser=async (phone)=>{
    let image="//www.baidu.com/s?wd=%E4%BB%8A%E6%97%A5%E6%96%B0%E9%B2%9C%E4%BA%8B&tn=SE_Pclogo_6ysd4c7a&sa=ire_dl_gh_logo&rsv_dl=igh_logo_pc";
    let sql="insert into user(username,image,phone,create_time) value(?,?,?,?)";
    let sqlarr = [phone,image,phone,(new Date()).valueOf()]
    let res = await dbconfig.sySqlConnect(sql,sqlarr);
    if(res.affectedRows == 1){
        //获取用户信息
        let user = await getUser(phone)
        //创建用户附表
        let userinfo= await createUserInfo(user[0].id)
        if(userinfo.affectedRows == 1){
            return user
        }else{
            return false
        }

    }else{
        return false
    }

}
//获取用户信息
let getUser = (username)=>{
    let sql="select * from user where id=? or phone=? or username=?"
    let sqlarr=[username,username,username]
    return dbconfig.sySqlConnect(sql,sqlarr)
}
//附表
let createUserInfo = (userid)=>{
    let sql="insert into  userinfo(useid,age,sex,job) values(?,?,?,?)"
    let sqlarr=[userid,18,2,'未设置']
    return dbconfig.sySqlConnect(sql,sqlarr)
}
//获取注册的用户详情
let getUserInfo = (userid)=>{
    let sql="select * from userinfo where useid=?"
    let sqlarr=[userid]
    return dbconfig.sySqlConnect(sql,sqlarr)
}
//模拟发送验证码
sendCode=(req,res)=>{
    // let phone=req.body.phone;
    let phone=req.query.phone;
    if(sendCodeP(phone)){
        res.send({
            'code':400,
            'msg':"已经发送过验证码，稍后再发"
        })
    }
    let code=rand(1000,9999);
    validatePhoneCode.push({
        'phone':phone,
        'code':code
    })
    res.send({
        'code':200,
        'msg':'发送成功',
    })
    console.log(code)
}
//验证码登录接口
codePhoneLogin = async(req,res)=>{
    let {phone,code}=req.query;
    //手机号是否发送过验证码
    if(sendCodeP(phone)){
        //手机号验证码是否拼配
        let status = findCodeAndPhone(code,phone)

        if(status == 'login'){
            let user =  await phoneLoginBind(phone)
            res.send({
                'code':200,
                'msg':'登录成功',
                'data':user[0],
            })
        }else if(status == 'error'){
            res.send({
                'code':200,
                'msg':'登录失败'
            })
        }
    }else{
        res.send({
            'code':400,
            'msg':'未发送验证码',
        })
    }
}
//修改头像
editUserImg=(req,res)=>{
    if(req.file.length === 0){
        res.render("error",{"message":'上传文件不能为空'})
        return
    }else{
        let file =req.file
        fs.renameSync('./public/uploads/' + file.filename,'./public/uploads/' + file.originalname)
        res.set({
            'content-type':'application/json;charset=utf-8'
        });
        let {user_id}=req.query
        let imgurl='http://localhost:3000/uploads/'+file.originalname
        let sql="update user set image=? where id=?"
        let sqlArr=[imgurl,user_id]
        dbconfig.sqlConnect(sql,sqlArr,(err,data)=>{
            if(err){
                console.log(err)
                throw'出错了'

            }else{
                if(data.affectedRows==1){
                    res.send({
                            'code':200,
                            'msg':"修改成功",
                            'url':imgurl,
                            })
                }else{
                    res.send({
                        'code':400,
                        'msg':"修改失败",
                        'url':'',
                        })
                }
            }
        })


    }
}
//多图上传
uploadMoreImage=(req,res)=>{
    let files = req.files
    if(req.files.length === 0){
        res.render("error",{"message":'上传文件不能为空'})
        return
    }else{
        for (var i in files) {
            res.set({
                'content-type':'application/json;charset=utf-8'
            });
            let file =file[i]
            fs.renameSync('./public/uploads/' + file.filename,'./public/uploads/' + file.originalname)
            let {user_id}=req.query
            let imgurl='http://localhost:3000/uploads/'+file.originalname
            // let sql="update user set image=? where id=?"
            // let sqlArr=[imgurl,user_id]
            // dbconfig.sqlConnect(sql,sqlArr,(err,data)=>{
            //     if(err){
            //         console.log(err)
            //         throw'出错了'
    
            //     }else{
            //         if(data.affectedRows==1){
            //             res.send({
            //                     'code':200,
            //                     'msg':"修改成功",
            //                     'url':imgurl,
            //                     })
            //         }else{
            //             res.send({
            //                 'code':400,
            //                 'msg':"修改失败",
            //                 'url':'',
            //                 })
            //         }
            //     }
            // })
        }
    }
}
module.exports={
    sendCode,codePhoneLogin,editUserImg
}
